package org.test.connectDB.comm;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.dgm.dgmJar.propertyUtil.DCommProperty;

/**
 * OracleDataBaseComm
 * 
 * @author：denggm@asiainfo-linkage.com
 * @Nov 12, 2012 11:14:29 AM
 * 
 * Copyright asiainf-linkage Corporation 2012
 */
public class OracleDataBaseComm extends AbstraceDataBaseComm implements IDBOper {
	Logger log = Logger.getLogger(this.getClass());

	public OracleDataBaseComm(String dataBasePropertiesName) throws Exception {
		this.dataBaseProperties = DCommProperty
				.getPropertyInstance(dataBasePropertiesName);
		if (dataBaseProperties == null || dataBaseProperties.size() < 1) {
			throw new Exception();
		}
		String dburl = dataBaseProperties
				.getProperty(AbstraceDataBaseComm.dburl);
		String userName = dataBaseProperties
				.getProperty(AbstraceDataBaseComm.userName);
		String password = dataBaseProperties
				.getProperty(AbstraceDataBaseComm.password);
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			this.conn = DriverManager.getConnection(dburl, userName, password);
			this.stmt = conn.createStatement();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			log.error("数据库连接错误，请检查数据库连接配置");
			e.printStackTrace();
		}
	}

	@Override
	public List queryByPage(String sql, int pageNum, int itemNum) {
		ResultSet rs = null;
		List resultList = null;
		try {
			// 计算rownum
			int startNum = itemNum * (pageNum - 1) + 1;
			int endNum = itemNum * pageNum;

			// 分页处理
			String pagesql = "select * from ( select page.*,rownum rn from "
					+ "(#sql)page  where rownum <= #endNum )outpage where outpage.rn >=#startNum";
			pagesql = pagesql.replace("#sql", sql);
			pagesql = pagesql.replace("#endNum", endNum + "");
			pagesql = pagesql.replace("#startNum", startNum + "");

			
			Connection conn = this.getConn();
			Statement stmt = conn.createStatement();
			System.out.println(pagesql);
			rs = stmt.executeQuery(pagesql);
			resultList = convertList(rs);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return resultList;
	}

	@Override
	public void close() throws SQLException {
		// TODO Auto-generated method stub
		this.getConn().close();
	}



}
